// 定义小仓库
import {defineStore} from "pinia";
import request from "@/utils/request";
import router from "@/router";
import {formatAddRoute} from "@/utils/tools";
import {asyncRoute} from "@/router";
import HttpClient from "@/utils/HttpClient";

const routes = [{
    path: '/index/index',
    name: 'Index',
    code: 'Index',
    children: []
}]
// 第一个仓库：小仓库名字 第二个参数：小仓库配置对象
const userStore = defineStore('user', {
    // 存储数据
    state: () => {
        const menuListString = sessionStorage.getItem('menuList')
        return {
            userInfo: {},
            menuList: menuListString ? JSON.parse(menuListString) : []
        }
    },
    actions: {
        // 注意：函数没有context上下文对象
        async saveMenuList() {
            console.log(this)
            const res: any = await HttpClient.get('/api/getMenuList')
            console.log(111, res)
            this.menuList = res.data
            sessionStorage.setItem('menuList', JSON.stringify(res.data))
            routes[0].children = this.menuList
            const asyncRouteData = formatAddRoute(routes)
            // console.log(888, asyncRouteData)
            asyncRoute.map(item => {
                if (!router.hasRoute(item.name)) {
                    router.addRoute('Index', item)
                }
            })
            // console.log(232, router)
        },
        saveUserInfo(data: object) {
            sessionStorage.setItem('userInfo', JSON.stringify(data))
            this.userInfo = data
        },
        handleOut() {
            sessionStorage.clear()
            router.push({
                path: '/'
            })
        }
    },
    getters: {
        getMenuList() {
            // console.log(123, this.menuList)
            const data = this.menuList as []
            return data
        },
        getUserInfo() {
            const userInfo = this.userInfo as object
            return userInfo
        }
    }
})

// 对外暴露方法
export default userStore
